// +----------------------------------------------------------------------
// | CmsWing [ 美业管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 psi All rights reserved.
// +----------------------------------------------------------------------
// | Author: huang <2374266244@qq.com>
// +----------------------------------------------------------------------
'use strict';
import Base from './base.js';

export default class extends Base {
  /*
   * index action
   * @return {Promise} []
  */
  
	async indexAction(){	
		let id = this.get('id');
		if(!id){
			//跳转404
			this.http.fail = new Error('传值错误，找不到该店铺！');
			think.statusAction(404, this.http);
		}
		//取基本信息
		let shop = await this.model('or_shop').where({id:id}).find();	
		//取详细信息
		let shopinfo = await this.model('or_shopinfo').where({s_id:id}).find();
		let data = {
			"shop":shop,
			"shopinfo":shopinfo
		}
		return this.json(data);
	}

	async addshopAction(){

		let orid = this.userinfo.departmentid;
		//判断是否超出店家数量
		let nownum = await this.model('or_department').where({pid: orid}).select();
		let yunnum = await this.model('or_department_info').where({departmentid: orid}).find();

		if(yunnum.gnum <= nownum.length){
			return this.fail('分店数量超出，已不能再添加！');
		}

		// 写入数据
		let dats = this.post();

		let model = this.model('or_shopinfo');

		await model.transaction(async () => {
			try{
				let dinfo = await this.model('or_department').db(model.db()).where({id: orid}).find();

				let adddata = {
					name: dats.name,
					pid: orid,
					floor: 1,
					orcode: dinfo.orcode,
				}

				let res1 = await this.model('or_department').db(model.db()).add(adddata);

				let shopinfo = {
					s_id : res1,
					phone : dats.phone,
					address : dats.address,
					province: dats.province,
					city: dats.city,
					area: dats.area
				}
				let res2 = await model.add(shopinfo);

				if(res1 && res2){
					await model.commit();
					return this.success("操作成功");
				}else{
					await model.rollback();
					return this.fail('操作失败！');
				}
			} catch(e) {
				console.log(e)
				await model.rollback();
				return this.fail('操作失败！');
			}
		})
	}
	
   
   
	async editshopAction(){

		let data = this.post();

		let model = this.model('or_shopinfo');

		await model.transaction(async () => {
			try {

				let sInfo = await model.where({s_id: data.id}).find();

				// 分店名称判断，根据地址不同可以使用同一个名称，直接做更新操作
				let updateDepartment = await this.model('or_department').db(model.db()).where({id: data.id}).update({name: data.name});

				let upRes = {
					phone: data.phone,
					province: data.province,
					city: data.city,
					area: data.area,
					address: data.address
				}

				let updateShop = await model.where({id: sInfo.id}).update(upRes);

				if (updateDepartment && updateShop) {
					await model.commit();
					return this.success('编辑成功');
				} else {
					await model.rollback();
					return this.fail('编辑失败')
				}

			} catch(e) {
				console.log(e);
				await model.rollback();
				return this.fail('编辑失败')
			}
		})
	}

	// 停用、启用分店
	async unstopAction(){
		let data = this.post();
		let res = await this.model('or_department').where({id: data.id}).update({isdisable: data.st});
		if (data.st*1) return res?this.success('关闭成功'):this.fail('关闭失败');
		else return res?this.success('开启成功'):this.fail('开启失败');
	}
	
	async userlistAction(){
		let id = this.get('id');
		//根据id取出店铺下面的前台用户
		let ulist = await this.model('or_shop_admin').alias("ou").field('ou.id,ou.username,ou.nickname,ou.headimg,ou.phone,og.name,og.code,ou.status').join("think_organization og ON ou.o_id = og.id").where({s_id:id}).select();
		let relist = {
            "draw": '',
            "data": ulist,
            "breadcrumb":''
        }
		return this.json(relist);
	}
	
	async adduserAction(){
		if(this.isPost){
			//查询该店铺下是否存在相同的用户
			let is_exist = await this.model('or_shop_admin').where({username:this.post('username')}).find();
			if(!think.isEmpty(is_exist)){
				return this.fail('该登陆账号已经存在！');
			}
			//查询机构的id和编码
			let data = this.post();
			data['o_id'] = this.userinfo.o_id;
			data['o_code'] = this.userinfo.o_code;
			data['password'] = think.md5(data['password']);
			let res = await this.model('or_shop_admin').add(data);
			return res?this.success({info:"添加成功！"}):this.fail('添加失败！');
		}
		let id = this.get('id');
		//取出id
		this.assign('s_id',id);
		return this.display();
	}
	
	async edituserAction(){
		if(this.isPost){
			let data = this.post();
			data['password']?data['password'] = think.md5(data['password']):delete data['password'];
			//判断用户名是否重复
			let is_exist = await this.model('or_shop_admin').where({username:data.username,id: ["!=",data.id]}).find();
			if(!think.isEmpty(is_exist)){
				return this.fail('此用户名已经存在！');
			}
			let res = await this.model('or_shop_admin').where({id:this.post('id')}).update(data);
			return res?this.success({info:"编辑成功！"}):this.fail('编辑失败！');
		}
		let id = this.get('id');
		let uinfo = await this.model('or_shop_admin').where({id:id}).find();
		return this.json(uinfo);
	}
	
	//禁用员工
	async disableAction(){
		let id = this.post('id');
		let status = this.post('status');
		let data = {};
		data['status'] = 1 == status?0:1;
		let res = await this.model('or_shop_admin').where({id:id}).update(data);
		return res?this.success({info:"操作成功！"}):this.fail('操作失败！');	
	}
	
	//删除员工
	async deleteuserAction(){
		let id = this.post('id');	
		let res = await this.model('or_shop_admin').where({id:id}).delete();
		return res?this.success({info:"删除成功！"}):this.fail('删除失败！');
	}

	async shoplistAction(){
		let page = this.post();
		let pages = page.pages;
		let limits = page.limits;
		let search = page.search;
		let zt = page.zt;
		let shopid = this.userinfo.departmentid;

		let data = await this.model('or_department')
				.alias('d')
				.field('d.*,di.phone,di.province,di.city,di.area,di.address')
				.join('`think_or_shopinfo` di on di.s_id=d.id')
				.where({'d.pid': shopid, 'd.isdisable': zt, 'd.name': ['like','%'+search+'%']})
				.page(pages, limits)
				.order('d.id DESC')
				.countSelect();

		return this.json(data);	
	}


	async signAction(){
		let list = await this.model('sigin').limit(1,10000).select();
		return this.json(list);
	}

	async adminlistAction(){
		let shopid = this.post('shopid');
		let alist = await this.model('or_admin')
				.alias('oa')
				.field('oa.*, r.gradeid, r.remarks')
				.join('think_or_rule_admin r on r.id = oa.groupid')
				.where({'oa.departmentid':shopid,'oa.ismain':1})
				.select();
		return this.json(alist);
	}

	async addadminAction(){
		let data = this.post();

		if (data.id*1) {
			let chongfu = await this.model('or_admin').where({username: data.username, id: ['!=', data.id]}).find();
			if (!think.isEmpty(chongfu)) {
				return this.fail('帐号重复');
			}

			data.password = think.md5(data.username);

			let gengxin = await this.model('or_admin').update(data);
			return gengxin?this.success('更改成功'):this.fail('更改失败');
		}

		//判断是否存在该用户
		let isexist = await this.model('or_admin').where({username:data.username}).find();
		if(!think.isEmpty(isexist)){
			return this.fail('此账号已经存在！');
		}
		// 判断当前店是否有主管理员
		let ismain = await this.model('or_admin').where({departmentid:data.departmentid, ismain:1}).find();
		if (!think.isEmpty(ismain)) {
			return this.fail('当前分店有管理员！')
		}		

		data.ismain = 1;
		data.groupid = 2;
		data.password = think.md5(data.username);
		data.phone = data.username;

		let res = await this.model('or_admin').add(data);

		return res?this.success('操作成功'):this.fail('操作失败');

	}
}